package com.leyou.trade.utils;

import com.github.wxpay.sdk.WXPay;
import com.github.wxpay.sdk.WXPayConfigImpl;
import com.github.wxpay.sdk.WXPayConstants;
import com.github.wxpay.sdk.WXPayUtil;
import com.leyou.common.exceptions.LyException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;

/**
 * @author 虎哥
 */
@Slf4j
@Component
public class PayHelper {

    private final WXPayConfigImpl payConfig;
    private final WXPay wxPay;

    public PayHelper(WXPayConfigImpl payConfig) {
        this.payConfig = payConfig;
        try {
            this.wxPay = new WXPay(payConfig, payConfig.getNotifyUrl());
        } catch (Exception e) {
            log.error("初始化微信客户端失败！");
            throw new LyException(500, e.getMessage());
        }
    }

    /*public Integer queryPayStatus(Long orderId){
        // 1.请求参数：
        Map<String, String> req = new HashMap<String, String>();
        req.put("out_trade_no", orderId.toString());

        // 2.发请求
        Map<String, String> resp = wxPay.orderQuery(req);
    }*/

    public String getPayUrl(Long orderId, String desc, Long totalFee) {
        // 1.请求参数：
        Map<String, String> data = new HashMap<String, String>();
        // 1.1.商品信息
        data.put("body", desc);
        // 1.2.订单编号
        data.put("out_trade_no", orderId.toString());
        // 1.3.支付金额
        data.put("total_fee", totalFee.toString());
        // 1.4.终端IP
        data.put("spbill_create_ip", payConfig.getSpbillCreateIp());
        // 1.5.交易类型
        data.put("trade_type", payConfig.getTradeType());  // 此处指定为扫码支付

        try {
            // 2.下单请求
            Map<String, String> resp = wxPay.unifiedOrder(data);


            // 3.验证
            // 3.1.验证returnCode
            checkReturnCode(resp);
            // 3.2.验证resultCode
            checkResultCode(resp);
            // 3.3.验证签名
            checkSignature(resp);

            // 4.获取支付链接
            String url = resp.get("code_url");
            if (url == null) {
                throw new RuntimeException("支付链接为空！");
            }
            return url;
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    public void checkSignature(Map<String, String> resp) throws RuntimeException {
        boolean isValid = false;
        try {
            isValid = WXPayUtil.isSignatureValid(resp, payConfig.getKey(), WXPayConstants.SignType.HMACSHA256);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        if (!isValid) {
            // 签名无效
            throw new RuntimeException("无效的签名！");
        }
    }

    public void checkResultCode(Map<String, String> resp) {
        String resultCode = resp.get("result_code");
        if ("FAIL".equals(resultCode)) {
            // 失败
            throw new RuntimeException(resp.get("err_code_des"));
        }
    }

    public void checkReturnCode(Map<String, String> resp) {
        String returnCode = resp.get("return_code");
        if ("FAIL".equals(returnCode)) {
            // 失败
            throw new RuntimeException(resp.get("return_msg"));
        }
    }
}
